<template>
    <view class="authentication">
        <view class="base">
            <view class="row flex_b">
                <view class="label">姓名</view>
                <view class="value">
                    <up-input inputAlign="right" placeholder="请输入你的真实姓名" border="none" v-model="form.nickname">
                    </up-input>
                </view>
            </view>
            <view class="row flex_b">
                <view class="label">手机号码</view>
                <view class="value">
                    <up-input inputAlign="right" type="number" placeholder="请输入手机号码" border="none"
                        v-model="form.userMobile">
                    </up-input>
                </view>
            </view>
            <view class="tips">
                <text style="color: red;">*</text>
                请填写真实姓名和手机号码，方便能平台和客户能与及时与您获得联系。
            </view>
        </view>
        <view class="base" style="padding: 24rpx;" v-if="role == 'worker'">
            <view class="title">身份认证</view>
            <view class="row flex_b">
                <view class="label">身份证号</view>
                <view class="value">
                    <up-input inputAlign="right" type="idcard" placeholder="请输入身份证号" border="none"
                        v-model="form.idNumber">
                    </up-input>
                </view>
            </view>
            <view class="row flex_b">
                <view class="label">选择身份证有效期</view>
                <view class="value flex_r">
                    <view style="margin-right: 12rpx;">是否长期</view>
                    <up-switch size="22" inactiveColor="#F2F2F2" activeColor="#FE6E04" v-model="isMax"></up-switch>
                </view>
            </view>
            <view class="row flex_b">
                <view class="date_range flex_c">
                    <view @click="showSelectCertBeginDate = true">
                        <up-input style="width: 250rpx;" inputAlign="center" v-model="form.certBeginDate" disabled
                            disabledColor="#ffffff" placeholder="请选择开始时间" border="none"></up-input>
                    </view>
                    <view style="width: 50rpx;text-align: center;">至</view>
                    <view @click="showSelectCertEndDate = true" v-if="!isMax">
                        <up-input style="width: 250rpx;" inputAlign="center" v-model="form.certEndDate" disabled
                            disabledColor="#ffffff" placeholder="请选择结束时间" border="none"></up-input>
                    </view>
                    <view v-else>
                        <up-input style="width: 250rpx;" inputAlign="center" modelValue="长期" disabled
                            disabledColor="#ffffff" placeholder="请选择结束时间" border="none"></up-input>
                    </view>
                </view>
            </view>
            <view class="uplaod">
                <view class="uplaod_title">上传身份证正面图片</view>
                <myUploadImg :imgList="idNumberFrontImageList" :max="1" @uploadImgSuccess="uploadImgSuccessFront"
                    @deleteImg="deleteImgFront">
                </myUploadImg>
            </view>
            <view class="uplaod">
                <view class="uplaod_title">上传身份证背面图片</view>
                <myUploadImg :imgList="idNumberBackList" :max="1" @uploadImgSuccess="uploadImgSuccessBack"
                    @deleteImg="deleteImgBack"></myUploadImg>
            </view>
            <view class="tips">
                <text style="color: red;">*</text>
                请填写本人身份证号，身份证号必须是18位，且与您的身份证上的信息一致，确保保险信息能成功录入。
            </view>
        </view>
        <view class="base" style="padding: 24rpx;" v-if="role == 'worker'">
            <view class="title">银行卡信息</view>
            <!-- <view class="row flex_b">
                <view class="label">开户行</view>
                <view class="value">
                    <up-input inputAlign="right" placeholder="请输入开户行" border="none" v-model="form.openingBank">
                    </up-input>
                </view>
            </view>
            <view class="row flex_b">
                <view class="label">开户支行</view>
                <view class="value">
                    <up-input inputAlign="right" placeholder="请输入开户支行" border="none"
                        v-model="form.accountOpeningBranch">
                    </up-input>
                </view>
            </view> -->
            <view class="row flex_b">
                <view class="label">银行卡号</view>
                <view class="value">
                    <up-input inputAlign="right" placeholder="请输入银行卡号" border="none"
                        v-model="form.bankCardNumber">
                    </up-input>
                </view>
            </view>
            <view class="row flex_b">
                <view class="label">选择银行卡所属省</view>
                <view class="value" @click="showSelectProvince = true">
                    <up-input style="width: 250rpx;" inputAlign="right" v-model="form.provinceName" disabled
                        disabledColor="#ffffff" placeholder="选择银行卡所属省" border="none"></up-input>
                </view>
            </view>
            <view class="row flex_b">
                <view class="label">选择银行卡所属市</view>
                <view class="value" @click="showSelectCity = true">
                    <up-input style="width: 250rpx;" inputAlign="right" v-model="form.cityName" disabled
                        disabledColor="#ffffff" placeholder="选择银行卡所属市" border="none"></up-input>
                </view>
            </view>
            <view class="uplaod">
                <view class="uplaod_title">上传银行卡照片</view>
                <myUploadImg :imgList="bankCardImageList" :max="1" @uploadImgSuccess="uploadImgSuccessBankCard"
                    @deleteImg="deleteImgBankCard">
                </myUploadImg>
            </view>
            <view class="tips">
                <text style="color: red;">*</text>
                请填写本人身份证开户的银行卡账号，否则将会提现失败!
            </view>
        </view>
        <view class="describe" v-if="role == 'worker'">
            <text style="color: red;margin-right: 6rpx;">*</text>
            如果您的身份信息已经审核通过，修改
            <text style="font-weight: bold;text-decoration-line: underline;">身份认证</text>和
            <text style="font-weight: bold;text-decoration-line: underline;">银行卡</text>
            相关信息后仍需要重新审核，请谨慎修改，以免影响后续提现相关操作。
        </view>
        <view class="bottom_btn">
            <view class="btn flex_c" @click="submit">确定</view>
        </view>
    </view>
    <!-- 选择身份证有效期(开始) -->
    <u-datetime-picker ref="datetimePickerRef" :minDate="-631180800000" :maxDate="new Date().getTime()"
        :formatter="formatter" :show="showSelectCertBeginDate" v-model="certBeginDate" mode="date"
        confirmColor="#FE6E04" @cancel="showSelectCertBeginDate = false"
        @confirm="confirmSelectCertBeginDate"></u-datetime-picker>
    <!-- 选择身份证有效期(结束) -->
    <u-datetime-picker ref="datetimePickerRef2" :minDate="new Date().getTime()" :maxDate="2524579200000"
        :formatter="formatter" :show="showSelectCertEndDate" v-model="certEndDate" mode="date" confirmColor="#FE6E04"
        @cancel="showSelectCertEndDate = false" @confirm="confirmSelectCertEndDate"></u-datetime-picker>
    <!-- 选择省 -->
    <up-picker title="选择省" :show="showSelectProvince" :columns="provinceList" keyName="provinceName"
        @close="closeSelectProvince" closeOnClickOverlay @cancel="showSelectProvince = false"
        @confirm="selectProvince"></up-picker>
    <!-- 选择市 -->
    <up-picker title="选择市" :show="showSelectCity" :columns="cityList" keyName="cityName" @close="closeSelectCity"
        closeOnClickOverlay @cancel="showSelectCity = false" @confirm="selectCity"></up-picker>
</template>

<script setup lang="ts">
import { computed, reactive } from 'vue';
import { onLoad, onReady, onShow } from '@dcloudio/uni-app';
import myUploadImg from '@/components/my-uploadImg/my-uploadImg.vue';
import { useMemberStore } from '@/stores'
import { updateMemberInfo, getMemberInfo, checkMemberMp, getUserRoleList } from '@/api/mine/userInfo'
import { getProvince, getCity } from '@/api/index/index'
import type { MemberInfo } from '@/types';
import { checkPhone, checkIdCard, checkChineseName, checkBankCard } from '@/utils/Validate';
import { ref } from 'vue';
import { getTimeDetial } from '@/utils';

const role = computed(() => {
    return uni.getStorageSync("role") || "customer"
})

const datetimePickerRef = ref<any | null>(null);
const datetimePickerRef2 = ref<any | null>(null);

const { setMemberInfo, setAuthInfo } = useMemberStore()

const form = reactive<MemberInfo>({
    nickname: "",
    avatar: '',
    userMobile: '',
    sex: '',
    idNumber: '',
    idNumberFrontImage: '',
    idNumberBackImage: '',
    certBeginDate: '',
    certEndDate: '',
    bankCardNumber: '',
    bankCardImage: '',
    provinceName: '',
    provinceCode: '',
    cityName: '',
    cityCode: ''
})
const idNumberFrontImageList = ref<string[]>([])
const idNumberBackList = ref<string[]>([])
const bankCardImageList = ref<string[]>([])

onShow(() => {
    checkMemberMpRes()
})
onLoad(() => {
    getMember()
    getProvinceList()
})
onReady(() => {
    // 微信小程序需要用此写法
    if (datetimePickerRef.value) {
        datetimePickerRef.value.setFormatter(formatter);
    }
    if (datetimePickerRef2.value) {
        datetimePickerRef2.value.setFormatter(formatter);
    }
});
// 查询是否关注公众号
const checkMemberMpResult = ref(false)
const checkMemberMpRes = async () => {
    const res: any = await checkMemberMp()
    if (res.code == 0 && res.data) {
        checkMemberMpResult.value = res.data
    }
}
// 获取用户个人信息
const getMember = () => {
    getMemberInfo().then((res: any) => {
        if (res.code == 0 && res.data) {
            setMemberInfo(res.data)
            const data = res.data
            form.avatar = data.avatar
            form.sex = data.sex
            form.idNumber = data.idNumber
            form.certBeginDate = data.certBeginDate
            form.certEndDate = data.certEndDate
            form.bankCardNumber = data.bankCardNumber
            form.provinceName = data.provinceName
            form.provinceCode = data.provinceCode
            form.cityName = data.cityName
            form.cityCode = data.cityCode
            form.idNumberFrontImage = data.idNumberFrontImage
            data.idNumberFrontImage && idNumberFrontImageList.value.push(data.idNumberFrontImage)
            form.idNumberBackImage = data.idNumberBackImage
            data.idNumberBackImage && idNumberBackList.value.push(data.idNumberBackImage)
            form.bankCardImage = data.bankCardImage
            data.bankCardImage && bankCardImageList.value.push(data.bankCardImage)
            form.userMobile = data.userMobile ?? data.mobile
            if (!checkChineseName(data.nickname)) {
                form.nickname = ''
            } else {
                form.nickname = data.nickname
            }
        }
    })
}

const submit = async () => {
    // 校验是否关注公众号
    if (!checkMemberMpResult.value) {
        uni.showModal({
            title: '请先关注公众号',
            content: '关注公众号可获得更详细的服务',
            showCancel: true,
            success: (res) => {
                if (res.confirm) {
                    uni.navigateTo({
                        url: '/pages/mine/official/official'
                    })
                }
            }
        })
        return
    }
    // 校验姓名
    if (!checkChineseName(form.nickname)) {
        uni.showToast({
            title: '请输入正确的姓名',
            icon: 'none'
        })
        return
    }
    // 校验手机号
    if (!checkPhone(form.userMobile)) {
        uni.showToast({
            title: '请输入正确的手机号',
            icon: 'none'
        })
        return
    }
    // 校验身份证号
    if (!checkIdCard(form.idNumber as string)) {
        uni.showToast({
            title: '请输入正确的身份证号',
            icon: 'none'
        })
        return
    }
    // 校验身份证有效期
    if (!form.certBeginDate) {
        uni.showToast({
            title: '请选择身份证有效期',
            icon: 'none'
        })
        return
    }
    if (!isMax && !form.certEndDate) {
        uni.showToast({
            title: '请选择身份证有效期',
            icon: 'none'
        })
        return
    }
    // 校验银行卡
    if (!checkBankCard(form.bankCardNumber)) {
        uni.showToast({
            title: '请输入正确的银行卡号',
            icon: 'none'
        })
        return
    }
    // 校验省
    if (!form.provinceName) {
        uni.showToast({
            title: '请选择银行卡所属省份',
            icon: 'none'
        })
        return
    }
    // 校验市
    if (!form.cityName) {
        uni.showToast({
            title: '请选择银行卡所属城市',
            icon: 'none'
        })
        return
    }
    // 图片
    if (!form.idNumberFrontImage) {
        uni.showToast({
            title: '请上传身份证正面',
            icon: 'none'
        })
        return
    }
    if (!form.idNumberBackImage) {
        uni.showToast({
            title: '请上传身份证背面',
            icon: 'none'
        })
        return
    }
    if (!form.bankCardImage) {
        uni.showToast({
            title: '请上传银行卡照片',
            icon: 'none'
        })
        return
    }
    try {
        if (isMax.value) {
            form.certEndDate = ''
        }
        uni.showLoading({
            title: '修改中...',
            mask: true
        })
        const res: any = await updateMemberInfo(form)
        if (res.code == 0 && res.data == 'ok') {
            uni.showToast({
                title: '修改成功'
            })
            await setMember()
            await setAuth()
            uni.hideLoading()
            setTimeout(() => {
                uni.switchTab({ url: '/pages/tabbar/mine/mine' })
            }, 500)
        } else {
            uni.hideLoading()
            uni.showToast({
                title: res.data,
                icon: 'none'
            })
        }

    } catch (error) {
        uni.hideLoading()
        console.log(error)
        uni.showToast({
            title: '操作失败',
            icon: 'none'
        })
    }
}
// 更新用户个人信息
const setMember = async () => {
    const res: any = await getMemberInfo()
    if (res.code == 0 && res.data) {
        setMemberInfo(res.data)
    }
}

// 更新认证信息
const setAuth = async () => {
    const res: any = await getUserRoleList()
    if (res.code == 0 && res.data.length > 0) {
        const data = res.data[0]
        setAuthInfo(data)
    }
}

// 选择身份证有效期
const formatter = (type: any, value: any) => {
    if (type === 'year') {
        return `${value}年`;
    }
    if (type === 'month') {
        return `${value}月`;
    }
    if (type === 'day') {
        return `${value}日`;
    }
    return value;
};
// 选择开始时间
const showSelectCertBeginDate = ref(false)
const certBeginDate = ref(new Date().getTime())
const confirmSelectCertBeginDate = (e: any) => {
    const { year, month, day } = getTimeDetial(e.value)
    form.certBeginDate = `${year}${month}${day}`
    showSelectCertBeginDate.value = false
}
// 选择结束时间
const showSelectCertEndDate = ref(false)
const certEndDate = ref(new Date().getTime())
const isMax = ref(false)
const confirmSelectCertEndDate = (e: any) => {
    const { year, month, day } = getTimeDetial(e.value)
    form.certEndDate = `${year}${month}${day}`
    showSelectCertEndDate.value = false
}
// 选择所在省
const showSelectProvince = ref(false)
const provinceList = ref([[]])
const getProvinceList = async () => {
    const res: any = await getProvince()
    if (res.code == 0 && res.data) {
        provinceList.value[0] = res.data
    }
}
const selectProvince = (e: any) => {
    cityList.value[0] = []
    form.cityName = ''
    form.cityCode = ''
    const { provinceName, provinceCode } = e.value[0]
    form.provinceName = provinceName
    form.provinceCode = provinceCode
    getCityList(provinceCode)
    showSelectProvince.value = false
}
const closeSelectProvince = () => {
    showSelectProvince.value = false
}
// 选择所在市
const showSelectCity = ref(false)
const cityList = ref([[]])
const getCityList = async (provinceCode: any) => {
    const res: any = await getCity(provinceCode)
    if (res.code == 0 && res.data) {
        const list = res.data.reduce((acc: any, cur: any) => {
            if (acc.findIndex((item: any) => item.cityName === cur.cityName) === -1) {
                acc.push({
                    cityName: cur.cityName,
                    cityCode: cur.cityCode
                })
            }
            return acc
        }, [])
        cityList.value[0] = list
    }
}
const selectCity = (e: any) => {
    const { cityName, cityCode } = e.value[0]
    form.cityName = cityName
    form.cityCode = cityCode
    showSelectCity.value = false
}
const closeSelectCity = () => {
    showSelectCity.value = false
}

// 上传身份证正面
const uploadImgSuccessFront = (url: string) => {
    form.idNumberFrontImage = url
}
const deleteImgFront = () => {
    form.idNumberFrontImage = ''
}

// 上传身份证背面
const uploadImgSuccessBack = (url: string) => {
    form.idNumberBackImage = url
}
const deleteImgBack = () => {
    form.idNumberBackImage = ''
}
// 上传银行卡
const uploadImgSuccessBankCard = (url: string) => {
    form.bankCardImage = url
}
const deleteImgBankCard = () => {
    form.bankCardImage = ''
}
</script>

<style lang="scss" scoped>
@import './authentication.scss';

.authentication {
    min-height: 100vh;
    background: #f8f8f8;
    overflow: hidden;
    padding-bottom: 200rpx;
    box-sizing: border-box;
}
</style>